package TCPMain;

import static TCPMain.Constant.ACTION_PROGRESS_UPDATE;
import static TCPMain.Constant.ACTION_PublishTask;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import TCPMain.utils.DataUtil;

public class FileService extends Service {
    JSONObject Task = new JSONObject();
    String TAG = "FileService";
    private final FileService.MyBinder binder = new FileService.MyBinder();
    private final ExecutorService threadPool = Executors.newFixedThreadPool(3);
    private ScheduledExecutorService scheduler;
    private List<Client> clients = new CopyOnWriteArrayList<>();

    public FileService() {
    }

    // 定义一个内部类，继承自 Binder
    public class MyBinder extends Binder {
        // 允许客户端调用 Service 的方法
        public FileService getService() {
            return FileService.this;
        }
    }

    // 添加发送广播方法
    private void sendProgressBroadcast(FileProgress progress, boolean isComplete) {
        Intent intent = new Intent(ACTION_PROGRESS_UPDATE);
        intent.putExtra("fileName", progress.getCurrentFileName());
        intent.putExtra("progress", progress.getProgress());
        intent.putExtra("downloaded", progress.getDownloadedSize());
        intent.putExtra("total", progress.getTotalSize());
        intent.putExtra("status", isComplete ? "complete" : "error");
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    private void sendProgressBroadcast(List<FileProgress> progresses, boolean isComplete) {
        Intent intent = new Intent(ACTION_PROGRESS_UPDATE);
        JSONObject data = new JSONObject();
        for (FileProgress progress : progresses) {
            try {
                data.put(progress.getCurrentFileName(), progress.getProgress());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        intent.putExtra("data", data.toString());
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    // 广播接收器
    private final BroadcastReceiver taskReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (ACTION_PublishTask.equals(intent.getAction())) {
                    // 解析广播数据
                    String task = intent.getStringExtra("Task");
                    Task = new JSONObject(task);
                    // 是否需要处理这个广播
                    if (Task.getString("Command").equals("SendFile")) {
                        threadPool.submit(() -> {
                            //处理文件请求
                            try {
                                Client client = new Client(Task.getString("IP"), Task.getInt("Port"));
                                clients.add(client);
                                Log.d(TAG, "SendFile:等待下载……");
                                DataUtil dataUtil = new DataUtil();
                                Task = dataUtil.GetData(Task);
                                boolean IsOk = client.SendFile(Task, new FileProgress());
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        });
                        // 发送广播通知 Activity
//                        Intent broadcastIntent = new Intent(ACTION_SendFolder);
//                        broadcastIntent.putExtra("FolderData", data.toString());
//                        LocalBroadcastManager.getInstance(FileService.this).sendBroadcast(broadcastIntent);
                    } else {
                        //丢弃广播
                        return;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 注册广播接收器
        IntentFilter filter = new IntentFilter("PublishTask");
        registerReceiver(taskReceiver, filter);
        // 创建一个调度器来处理后台任务
        //scheduler = Executors.newScheduledThreadPool(1);
        // 启动定期任务
        //scheduler.scheduleAtFixedRate(this::processUp, 0, 1, TimeUnit.SECONDS);
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    processUp();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Log.d(TAG, "onCreate");
    }

    /**
     * 定期处理后台任务->处理文件上传进度
     */
    private void processUp() throws InterruptedException {
        List<FileProgress> progresses = new ArrayList<>();
        while (clients.isEmpty()) {
            Thread.sleep(1000);
        }
        while (true) {
            Log.d(TAG, "processUp 文件传输对象数量: " + clients.size());
            for (Client client : clients) {
                if (client.isClose()) {// 判断client是否关闭
                    clients.remove(client);
                } else if (client.progress.getTotalSize() == 0) {//判断进度条是否初始化
                    continue;
                } else if (client.progress.getProgress()==99) {//判断是否下载完成
                    clients.remove(client);
                    progresses.remove(client.progress);
                    sendProgressBroadcast(progresses, false);// 发送进度更新广播
                } else if (client.progress == null) {//判断进度条是否初始化
                    continue;
                } else {// 判断进度条是否更新
                    progresses.add(client.progress);
                }
                sendProgressBroadcast(progresses, false);// 发送进度更新广播
            }
            Thread.sleep(1000);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);

    }
}